package harima.AGameServer.ServerSide.Threads;

import harima.AGameServer.ServerSide.IGameServer;
import harima.AGameServer.ServerSide.Exceptions.CannotAcceptClientsException;
import harima.AGameServer.ServerSide.Exceptions.CannotStartServerException;
import harima.AGameServer.ServerSide.Exceptions.CannotStopServerException;
import harima.AGameServer.ServerSide.Exceptions.ServerException;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class WaitForClientsThread implements Runnable {

	IGameServer server;
	ServerSocket serverSocket;
	
	public WaitForClientsThread(IGameServer ownerServer)
	{
		server = ownerServer;
	}

	public void run() {
		
		try {
			startServerSocket();			
			while(server.isRunning())
			{
				Socket client = acceptClient();
				server.addClient(client);
			}			
			stopServerSocket();
		} catch (ServerException e) {
			server.handleServerException(e);
		}
	}

	private Socket acceptClient() throws ServerException {
		Socket client = null;
		
		try {
			client = serverSocket.accept();
		} catch (IOException e) {
			throw new CannotAcceptClientsException(e);
		}
		
		return client;
	}

	public void startServerSocket() throws ServerException {
		
		try {
			serverSocket = new ServerSocket(server.getPort());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new CannotStartServerException(e);
		}
	}
	
	public void stopServerSocket() throws ServerException
	{
		if(serverSocket != null)
		{
			try {
				serverSocket.close();
			} catch (IOException e) {
				throw new CannotStopServerException(e);
			}		
		}
	}
}
